from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from core.models import StudentProfile
import csv

class Command(BaseCommand):
    help = '从学生清单中创建用户'

    def add_arguments(self, parser):
        parser.add_argument('--csv', type=str, help='学生清单的CSV文件路径')

    def handle(self, *args, **options):
        csv_file = options['csv']

        with open(csv_file, 'r', encoding='utf-8') as file:
            reader = csv.DictReader(file)
            for row in reader:
                try:
                    username = row['XH']  # 假设学号是用户名
                    
                    try:
                        user = User.objects.get(username='stu' + username)
                    except User.DoesNotExist:
                        user = User.objects.create(username='stu' + username,
                                                password=make_password(username),
                                                is_active=True
                                                )
                    print(user.username)
                    student_info = {
                        'user': user,
                        'student_id': row['XH'],  # 假设学号是XH字段
                        'student_name': row['XM'],  # 假设姓名是XM字段
                        'gender': 1 if row['XB'] == '男' else 0,  # 假设姓名是XM字段
                        'major': row['ZYMC'],
                        'enroll_year': row['XH'][:4],
                        'grade': row['BJMC'][:4],
                        'classname': row['BJMC'],
                    }
                    try:
                        student = StudentProfile.objects.get(student_id=row['XH'])
                        continue
                    except StudentProfile.DoesNotExist:
                        student = StudentProfile.objects.create(**student_info)

                    self.stdout.write(self.style.SUCCESS(f'成功创建用户 {username}'))
                except Exception as e:
                    self.stderr.write(self.style.ERROR(f'创建用户失败: {str(e)}'))
